#include "todoformatter.h"
#include "todoitem.h"
#include <QStringList>

TodoFormatter::TodoFormatter()
{
}

void TodoFormatter::addLine(const TodoItem &item, bool addCompleted)
{
    if( addCompleted && (!item.complete) )
        return;

    QVector<QString> line = _prepareStrings(item);

    _listItems.append( line );
}

QVector<QString> TodoFormatter::_prepareStrings(const TodoItem &item)
{
    QVector<QString> itemStrings;

    itemStrings.resize(8);

    itemStrings[0] = QString::number(item.code);
    itemStrings[1] = (item.urgent?"S":"N");
    itemStrings[2] = QString::number(item.priority);
    itemStrings[3] = item.description;
    itemStrings[4] = item.date.toString("dd/MM/yyyy");
    itemStrings[5] = (item.complete?"S":"N");

    if( item.priority < 3 ) {
        itemStrings[6] = "<font color='red'>";
        itemStrings[7] = "</font>";
    }
    if( item.urgent ) {
        itemStrings[6] += "<u>";
        itemStrings[7] += "</u>";
    }

    return itemStrings;
}

void TodoFormatter::calculateSizes()
{
    if( _listItems.size() == 0 ) return;

    _listSizes.resize( _listItems[0].size() );
    for(int i=0; i < _listSizes.size(); i++) {
        _listSizes[i] = 0;
    }

    for( const QVector<QString> &line : _listItems ) {

        for(int i=0; i < line.size(); i++) {
            const QString &item = line[i];
            if( item.size() > _listSizes[i] )
                _listSizes[i] = item.size();
        }

    }
}

QPair<int, QString> TodoFormatter::getHeader()
{
    QStringList headerItems;
    headerItems << "#"<< "U" << "pri" << "descricao" << "date";

    QString fmtStr;
    fmtStr.sprintf("%*.*s | %*.*s | %*.*s | %*.*s | %*.*s<br>",
            _listSizes[0], _listSizes[0], qPrintable(headerItems[0]),
            _listSizes[1], _listSizes[1], qPrintable(headerItems[1]),
            _listSizes[2], _listSizes[2], qPrintable(headerItems[2]),
            _listSizes[3], _listSizes[3], qPrintable(headerItems[3]),
            _listSizes[4], _listSizes[4], qPrintable(headerItems[4])
            );

    int size = fmtStr.size() - 4; //<br>

    return qMakePair(size, fmtStr.replace(" ", "&nbsp;"));
}

QString TodoFormatter::getLine(int pos)
{
    QVector<QString> &line = _listItems[pos];

    QStringList list;
    list.reserve(line.size());

    //for(QString &s : line) {    
    for(int i=0; i < line.size() - 3; i++) { //-1 para tirar o complete
        list << QString("%1").arg(line[i], -_listSizes[i]);
    }

    QString sLine = list.join(" | ");
    sLine.replace(" ", "&nbsp;");
    return line[6] + sLine + line[7] + "<br>";
}

int TodoFormatter::getCount()
{
    return _listItems.count();
}
